#include "drv_wifi.h"
#include "drv_systick.h"
#include "string.h"
#include "drve_led.h"
//#include "drv_usart.h"
#include "drv_sht20.h"
#include "drv_duo.h"
#include "drv_motor.h"
#include "drv_time.h"
#include "yoled.h"
#include "oled.h"

#define USART3_MAX   128                   // 接收缓冲区最大长度

uint8_t usart3_buf[USART3_MAX] = {0};      // 接收缓冲区
uint8_t usart3_len = 0;                 // 当前接收数据的长度
uint8_t usart3_ready = 0;               // 一条完整命令接收完成标志
uint8_t wifi_data=0; 





//临时存储数据字符
#define CMD_WIFI_LEN 32                 // 命令缓冲区长度
 extern uint16_t fan_pwm1;
void drv_usart3_init(void)
{    
    GPIO_InitTypeDef  GPIO_InitStruct;
    USART_InitTypeDef  USART_InitStruct;
    NVIC_InitTypeDef  NVIC_InitStruct;
    //打开时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);//开启时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);//开启USART的
    //GPIO配置
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//复用
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//推挽
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_25MHz;
    GPIO_Init(GPIOB, &GPIO_InitStruct);
    //复用功能
    GPIO_PinAFConfig(GPIOB,GPIO_PinSource10, GPIO_AF_USART3);
    GPIO_PinAFConfig(GPIOB,GPIO_PinSource11, GPIO_AF_USART3);    
    //串口配置
    USART_InitStruct.USART_BaudRate = 115200;
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//硬件控流
    USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_InitStruct.USART_Parity = USART_Parity_No;
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;//数据位
    USART_InitStruct.USART_StopBits = USART_StopBits_1;
    USART_Init(USART3, &USART_InitStruct);
    //接受中断
    USART_ClearFlag(USART3,USART_FLAG_TC); //清理标志位
    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
    //中断配置
    NVIC_InitStruct.NVIC_IRQChannel = USART3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_Init(&NVIC_InitStruct);
    //使能串口
    USART_Cmd(USART3,ENABLE);
}
/**************************************
函数名：usart_sendstr
函数功能：串口传输字符
输入参数：USARTx:串口 str:字符 size:字符长度
输出参数：无
其它：无
****************************************/
void  usart_sendstr(USART_TypeDef* USARTx,char *str,int size)
{
    uint8_t i = 0;
    USART_ClearFlag(USARTx, USART_FLAG_TC);
    for(i=0;i<size;i++)
    {
        USART_SendData(USARTx, *str);
        while(RESET == USART_GetFlagStatus(USARTx, USART_FLAG_TC));
        USART_ClearFlag(USARTx, USART_FLAG_TC);//清空发送完成标志
        str++;
    }
}




void drv_wifi_init(void)
{
	

	usart_sendstr(USART3,"AT+RESTORE\r\n",strlen("AT+RESTORE\r\n"));
	drv_systick_ms(5000);
	usart_sendstr(USART3,"AT+CWMODE=1\r\n",strlen("AT+CWMODE=1\r\n"));
	drv_systick_ms(5000);
	usart_sendstr(USART3,"AT+CWJAP_DEF=\"hqyjcs\",\"hqyj2022\"\r\n",strlen("AT+CWJAP_DEF=\"hqyjcs\",\"hqyj2022\"\r\n"));
	drv_systick_ms(10000);
	usart_sendstr(USART3,"AT+CIFSR\r\n",strlen("AT+CIFSR\r\n"));
	drv_systick_ms(5000);
	usart_sendstr(USART3,"AT+CIPMUX=0\r\n",strlen("AT+CIPMUX=0\r\n"));
	drv_systick_ms(5000);
	usart_sendstr(USART3,"AT+CIPSTART=\"TCP\",\"192.168.91.183\",8080\r\n",strlen("AT+CIPSTART=\"TCP\",\"192.168.91.183\",8080\r\n"));
	drv_systick_ms(10000);


}

void USART3_IRQHandler(void)
{       
    if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)   // 判断是否接收中断
    {
        USART_ClearITPendingBit(USART3, USART_IT_RXNE);     // 清除中断标志位
        
        // 读取接收到的数据
        wifi_data = USART_ReceiveData(USART3);
        
        // 数据转发到 USART6（调试用，可保留）
        USART_SendData(USART6, wifi_data);
        
        // 存储数据到缓冲区，用于命令识别
        if (usart3_len < USART3_MAX - 1)  // 检查数据长度是否溢出,预留一个位置给 '\0'
        {
            usart3_buf[usart3_len++]=wifi_data;    //数据存入buf
            // 判断是否接收到换行符或回车符（作为命令结束标志）
            if (wifi_data == '\n' || wifi_data == '\r')
            {
                usart3_ready = 1;                      // 标记一条完整数据接收完成
            }
        }
        else    
        {
            // 缓冲区满，强制复位（这里也不在中断里做命令判断，只是复位）
            usart3_len = 0;
            memset(usart3_buf, 0,CMD_WIFI_LEN );
        }
    }    
}
 


void wifi_command(void)
{
    uint8_t i;
    char *cmd;
    char *p = (char*)usart3_buf;
    cmd = NULL;

    // 找到最后一个冒号
    for(i = 0; i < usart3_len; i++)
    {
        if(p[i] == ':')
        {
            cmd = &p[i + 1];
        }
    }

    // 如果没有冒号，直接清空
    if(cmd == NULL)
    {
        usart3_ready = 0;
        usart3_len = 0;
        memset(usart3_buf, 0, USART3_MAX);
        return;
    }

    // 去掉结尾 \r 或 \n
    for(i = 0; i < usart3_len; i++)
    {
        if(cmd[i] == '\r' || cmd[i] == '\n')
        {
            cmd[i] = '\0';
            break;
        }
    }

    // 匹配命令 - 使用一致的 if-else if 结构
    if(strcmp(cmd, "ledopen") == 0)
    {
        drve_led_open1();
        GPIO_SetBits(GPIOC, GPIO_Pin_4);
        GPIO_SetBits(GPIOC, GPIO_Pin_3);
        GPIO_SetBits(GPIOC, GPIO_Pin_13);
		return;
    }
    else if(strcmp(cmd, "ledoff") == 0 || strcmp(cmd, "ledclose") == 0)
    {
        drve_led_close1();
        GPIO_ResetBits(GPIOC, GPIO_Pin_4);
        GPIO_ResetBits(GPIOC, GPIO_Pin_3);
        GPIO_ResetBits(GPIOC, GPIO_Pin_13);
		return;
    }
    else if(strcmp(cmd, "FAN0") == 0)
    {
        fan_pwm1 = 0;
        TIM_SetCompare1(TIM3, fan_pwm1);
		return;
    }
    else if(strcmp(cmd, "FAN1") == 0)
    {
        fan_pwm1 = 5000;
        TIM_SetCompare1(TIM3, fan_pwm1);
		return;
    }
    else if(strcmp(cmd, "FAN2") == 0)
    {
        fan_pwm1 = 7000;
        TIM_SetCompare1(TIM3, fan_pwm1);
		return;
    }
    else if(strcmp(cmd, "FAN3") == 0)
    {
        fan_pwm1 = 10000;
        TIM_SetCompare1(TIM3, fan_pwm1);
		return;
    }
  
    else if(strcmp(cmd, "open") == 0)
    {
        motor_open();
		return;
    }
    else if(strcmp(cmd, "close") == 0)
    {
        motor_close();
		return;
    }
    // 动作命令处理
    else if(strcmp(cmd, "up") == 0)
    {
        current_state = STATE_STANDUP;
        reset_dog_action();
		return;
    }
    else if(strcmp(cmd, "down") == 0)
    {
        current_state = STATE_LIEDOWN;
        reset_dog_action();
		return;
    }
    else if(strcmp(cmd, "run") == 0)
    {
        current_state = STATE_FRONT;
        reset_dog_action();
		return;
    }
    else if(strcmp(cmd, "back") == 0)
    {
        current_state = STATE_BACK;
        reset_dog_action();
		return;
    }
    else if(strcmp(cmd, "stop") == 0)
    {
        current_state = 0xFF;  // 停止状态
        reset_dog_action();
		return;
    }
		else if(strcmp(cmd, "ws") == 0)
			{
                      yoled ();  
				return;
				
			}
			else if(strcmp(cmd, "tp") == 0)
			{
                      BMP_8();  
				return;
				
			}
		else if(strcmp(cmd, "clear") == 0)
			{
                     OLED_Init() ;
				return;

			}
			else if(strcmp(cmd, "beep0") == 0)
			{
                     
							 GPIO_SetBits(GPIOA, GPIO_Pin_15);
					
				
				
			
				return;
			
			}
		else if(strcmp(cmd, "beep") == 0)
			{
                
					
							GPIO_ResetBits(GPIOA, GPIO_Pin_15);
				
				
				return;

			}
    // 清空缓冲区并重置标志
    usart3_ready = 0;
    usart3_len = 0;
    memset(usart3_buf, 0, USART3_MAX);
}

//串口中断
void USART6_IRQHandler(void)
{
	
	if(USART_GetITStatus(USART6, USART_IT_RXNE))
	{
		char data=USART_ReceiveData(USART6);			//读数据
		USART_ClearITPendingBit(USART6, USART_IT_RXNE);	//清处标志
		USART_SendData(USART6, data);					//传数据
	}
	//空闲中断,一个数据流传输完成
	if(USART_GetITStatus(USART6, USART_IT_IDLE))
	{
		USART_ClearITPendingBit(USART6, USART_IT_IDLE);
		USART_ReceiveData(USART6);
		USART_SendData(USART6,'n');
	}
}